package cn.wolfcode.luowowo.website.web.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = CookieUtil.getCookie(request, response);
        UserInfo userInfo = userInfoRedisService.getUserByToken(token);
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm =(HandlerMethod) handler;
            RequireLogin annotation = hm.getMethodAnnotation(RequireLogin.class);
            //System.out.println(annotation);
            if (annotation != null) {
                if (userInfo == null) {
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        //为什么这里也要存入session? 因为如果你在退出浏览器的情况下,session是会清空,那么如果你访问非主页的其他开放页面,将不会显示用户信息
        request.getSession().setAttribute("userInfo",userInfo);
        return true;
    }
}
